package com.example.excelimporter.service.impl;

import com.alibaba.excel.EasyExcel;
import com.example.excelimporter.listener.ExcelDataListener;
import com.example.excelimporter.listener.PostImportListener;
import com.example.excelimporter.listener.PostImportListenerFactory;
import com.example.excelimporter.model.ImportResult;
import com.example.excelimporter.model.TemplateConfig;
import com.example.excelimporter.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExcelImportServiceImpl implements ExcelImportService {

    @Autowired
    private TemplateConfigService templateConfigService;

    @Autowired
    private DataValidationService dataValidationService;
    
    @Autowired
    private DataMappingService dataMappingService;
    
    @Autowired
    private DataSaveService dataSaveService;

    @Autowired
    private PostImportProcessor postImportProcessor;

    @Autowired
    private PostImportListenerFactory listenerFactory;

    @Override
    public ImportResult importExcel(MultipartFile file, String templateId) throws IOException {
        TemplateConfig templateConfig = templateConfigService.getTemplateConfigById(templateId);
        if (templateConfig == null) {
            throw new IllegalArgumentException("Template not found");
        }

        ExcelDataListener listener = new ExcelDataListener(
            templateConfig,
            dataValidationService,
            dataMappingService,
            dataSaveService,
            postImportProcessor
        );

        try {
            EasyExcel.read(file.getInputStream(), templateConfig.getDataClass(), listener)
                    .sheet()
                    .doRead();

            ImportResult result = listener.buildImportResult();
            notifyListeners(templateConfig, result, null);
            return result;
        } catch (Exception e) {
            notifyListeners(templateConfig, null, e);
            throw e;
        }
    }

    @Override
    public void importExcel(TemplateConfig templateConfig, InputStream excelStream) {
        ExcelDataListener listener = new ExcelDataListener(
            templateConfig,
            dataValidationService,
            dataMappingService,
            dataSaveService,
            postImportProcessor
        );

        try {
            EasyExcel.read(excelStream, templateConfig.getDataClass(), listener)
                    .sheet()
                    .doRead();

            ImportResult result = listener.buildImportResult();
            notifyListeners(templateConfig, result, null);
        } catch (Exception e) {
            notifyListeners(templateConfig, null, e);
            throw e;
        }
    }

    private void notifyListeners(TemplateConfig templateConfig, ImportResult result, Exception error) {
        if (templateConfig.getListeners() == null) {
            return;
        }

        List<PostImportListener> listeners = templateConfig.getListeners().stream()
                .map(listenerFactory::createListener)
                .collect(Collectors.toList());

        for (PostImportListener listener : listeners) {
            try {
                if (error != null) {
                    listener.onError(templateConfig, error);
                } else {
                    listener.onSuccess(templateConfig, result);
                }
            } catch (Exception e) {
                // Log listener error but don't fail the import
                e.printStackTrace();
            }
        }
    }
}
